﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using WebApiOrm.Provider;

namespace WebApiOrm
{
    sealed class OrmBuilder : IOrmBuilder
    {
        public DatabaseType DatabaseType { get; }

        public string ConnectionString { get; }

        public IServiceCollection Services { get; }

        public OrmBuilder(DatabaseType databaseType, string connectionString, IServiceCollection services)
        {
            this.DatabaseType = databaseType;
            this.ConnectionString = connectionString;
            this.Services = services;
        }

        /// <summary>
        /// 从配置期Database获取DatabaseType
        /// 并根据DatabaseType获取对应的连接字符串
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IOrmBuilder Create(WebApplicationBuilder builder)
        {
            var databaseType = builder.Configuration.GetSection("Database").Get<DatabaseType>();
            Console.WriteLine($"{nameof(DatabaseType)}: {databaseType}");
            var connectionString = builder.Configuration.GetConnectionString(databaseType.ToString());
            Console.WriteLine($"ConnectionString: {connectionString}");
            return new OrmBuilder(databaseType, connectionString, builder.Services);
        }
    }
}
